package alg20241224;

import java.util.Random;

//int key = nums[new Random().nextInt((r - l + 1)) + l];
public class Text {
    public int findKthLargest(int[] nums, int k) {
         return qsort(nums, 0, nums.length - 1, k);
    }

    public int qsort(int[] nums, int l, int r, int k){
        if(l == r) return nums[l];
        int left = l - 1, right = r + 1, i = l;
        int key = nums[new Random().nextInt((r - l + 1)) + l];
        //划分三个区间  [l, left] [left, right] [right, r]
        while(i < right){
            if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] == key) i++;
            else swap(nums, --right, i);
        }
        //计算三个区间的个数
        int c = r - right + 1; //>key
        int b = right - left - 1;  //==key

        if(c > k) return qsort(nums, right, r, k);
        else if(b + c >= k) return key;
        else return qsort(nums, l, left, k - b - c);

    }
    public void swap(int[] nums, int i, int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

}
